﻿using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using EscapeZone.Mapping;
using EscapeZone.Mapping.Building;
using EscapeZone.Screens;

namespace EscapeZone.Serialization
{
    public class MapSerializer
    {
        private readonly XmlSerializer m_serializer;

        public MapSerializer()
        {
            m_serializer = new XmlSerializer(typeof(MapDefinition));

        }

        private MapDefinition LoadFile(string path)
        {
            using (FileStream stream = new FileStream(path, FileMode.Open))
            {
                MapDefinition definition = m_serializer.Deserialize(stream) as MapDefinition;

                return definition;
            }
        }

        public Map LoadMap(EscapeGame game, GameScreen screen, string mapName)
        {
            MapElementBuilder builder = new MapElementBuilder(game, screen);
            var def = LoadFile(mapName + ".xml");
            if (def != null)
            {

                List<IMapElement> elements = new List<IMapElement>();
                elements.AddRange(def.MapElements);
                elements.AddRange(builder.BuildElements(def.MapElementDefinitions));

                return new Map(game, screen, elements);
            }

            return null;
        }

        public void SaveMap(Map map, string name)
        {
            MapDefinition def = new MapDefinition();

            foreach (IMapElement mapElement in map.MapElements)
            {
                if (mapElement is IDefinable)
                {
                    def.MapElementDefinitions.Add(((IDefinable)mapElement).GetDefinition());
                }
                else
                {
                    def.MapElements.Add(mapElement);
                }
            }

            SaveMap(def, name);
        }

        public void SaveMap(MapDefinition definition, string name)
        {
            using (FileStream stream = new FileStream(name + ".xml", FileMode.Create))
            {
                m_serializer.Serialize(stream, definition);
            }
        }

    }
}